/*
 
 */

package ritcs.sensors.app;

import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.*;
import java.util.logging.Level;
import com.microsoft.sqlserver.jdbc.*;
import java.util.logging.Logger;
/**
 *
 * @author chimbs
 */
public class Database {

    String ieee;
    int id;
    Connection conn;
    public Database(String ieee){
        try {

            
          //  System.setProperty("java.library.path", "C:/Windows/System32/");
            System.out.println(System.getProperty("java.library.path"));
            //System.setProperty("java.library.path", "C:\\Windows\\System32\\");
               // Driver d = (Driver) Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance();
                conn = DriverManager.getConnection("jdbc:sqlserver://CHIMBS-PC\\CHIMBS;databaseName=sensors;integratedSecurity=true; ");
                
                String query = "select * from [sensor] where sensor_name = ?";
                PreparedStatement ps = conn.prepareStatement(query);
                ps.setString(1, ieee);
                ResultSet rs = ps.executeQuery();
                System.out.println(ps.toString());
                boolean present = false;

                while(rs.next()){
                    present = true;
                    this.id= rs.getInt("sensor_id");
                }

                if(!present){
                    String insertQuery = "insert into sensor (sensor_name) values (?)";
                    PreparedStatement ps2 = conn.prepareStatement(insertQuery);
                    ps2.setString(1, ieee);
                    ps2.executeUpdate();
                    rs = ps.executeQuery();
                    rs.next();
                    id = rs.getInt("sensor_id");

            }

                System.out.println("ID is : "+this.id);
                }




            
        catch(SQLException ex){
        }
             


    }
    public void recordReading(Timestamp d , float value, float light) throws SQLException{


       String query = "INSERT INTO [sensors].[dbo].[Reading]([reading_date],[sensor_id],[sensor_reading], [temp_reading]) VALUES (?, ?,?,?)";

       PreparedStatement ps = conn.prepareStatement(query);
       ps.setTimestamp(1, d);
       ps.setInt(2, this.id);
       ps.setFloat(3, value);
       ps.setFloat(4, light);
       ps.execute();
       


    }



}
